#include <network.h>

static int connect_host(char *host)
{
	int sockfd;
	char temp_ip[16];
	struct hostent *hent;
	struct sockaddr_in remote;

	if( (sockfd=socket(AF_INET, SOCK_STREAM, 0)) < 0 )
		return -1;

//	if( (hent=gethostbyname(host)) == NULL )
//		return -1;

	bzero(&remote, sizeof(remote));

	// Family
	remote.sin_family = AF_INET;

	// Address
//	inet_ntop(AF_INET, (void *)hent->h_addr_list[0], temp_ip, 15);
	inet_aton(/*temp_ip*/"68.64.47.244", &remote.sin_addr);

	// Port
	remote.sin_port = htons(80);

	if( connect(sockfd, (struct sockaddr *)&remote, sizeof(remote)) != 0 )
		return -1;

	return sockfd;
}

static int send_packet(int sockfd, char *packet)
{
	int i, count = 0;
	while( count < strlen(packet) )
	{
		i = send(sockfd, packet+count, strlen(packet)-count, 0);
		if(i==-1)
			return -1;
		count += i;
	}
	return count;
}

static char *recv_packet(int sockfd)
{
	int i, count = 0;
	char *buf = NULL, temp_string[1024];
	while( (i=recv(sockfd,temp_string,sizeof(temp_string),0)) > 0 )
	{
		if( (buf=(char *)realloc(buf, count+i)) == NULL )
			return NULL;

		memcpy(buf+count, &temp_string[0], i);
		count += i;
	}
	return buf;
}

char *get_page(char *host, char *uri)
{
	int sockfd;
	char *buf;

	if( (sockfd=connect_host(host)) < 0 )
		return NULL;

	buf = (char *)malloc(
		strlen("POST ") + strlen(uri) + strlen(" HTTP/1.1") + strlen("\r\n") +
		strlen("Host: ") + strlen(host) + strlen("\r\n") +
		strlen("\r\n") +
		1
	);
	sprintf(buf, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", uri, host);

	if( send_packet(sockfd, buf) < 0 )
	{
		free(buf);
		return NULL;
	}

	if( (buf=recv_packet(sockfd)) == NULL )
		return NULL;

	return buf;
}

char *post_page(char *host, char *uri, char *data)
{
	int sockfd;
	char *buf;

	if( (sockfd=connect_host(host)) < 0 )
		return NULL;

	buf = (char *)malloc(
		strlen("POST ") + strlen(uri) + strlen(" HTTP/1.1") + strlen("\r\n") +
		strlen("Host: ") + strlen(host) + strlen("\r\n") +
		strlen("Content-Length: 12345") + strlen("\r\n") +
		strlen("\r\n") +
		strlen(data) +
		1
	);
	sprintf(buf, "POST %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\n\r\n%s", uri, host, strlen(data), data);

	if( send_packet(sockfd, buf) < 0 )
	{
		free(buf);
		return NULL;
	}

	if( (buf=recv_packet(sockfd)) == NULL )
		return NULL;

	return buf;

}
